#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;
using System.Collections;
using Gizmox.WebGUI.Common.Resources;
using System.IO;
using QueryBuilder;
using TVC.Layout;
using TVC.Report;
using FlexCel.Core;
using System.Text.RegularExpressions;
using Gizmox.WebGUI.Common.Gateways;

#endregion

namespace TVC.Modules.Rep
{
    public partial class QRS : ModuleParent, IHostedApplication
    {
        //string _processStatus = "";
        //string _strType = "QD";
        //string sErr = "";
        GridLayout layout = null;
        string _datePaterm = @"^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{3}|[0-9]{2}|[0-9]{1})$";
        string _currentQD = "";
        public QRS()
        {
            InitializeComponent();
            _strType = "QD";
        }
        int idAllowEditLanguage = 1;
        int idFilter = 15;
        int idPreview = 16;
        int idExcel = 17;
        int idPrint = 18;
        int idclsTransferIn = 19;
        int idclsTransferOut = 20;



        protected override void AllowEditLanguage()
        {
            //foreach (Control x in this.Controls)
            //{
            //    if (x is Label)
            //    {
            //        x.DoubleClick += Control_DoubleClick;
            //    }
            //    if (x is GroupBox || x is ExpandableGroupBox || x is Panel)
            //    {
            //        x.DoubleClick += Control_DoubleClick;
            //        foreach (Control y in x.Controls)
            //        {
            //            y.DoubleClick += Control_DoubleClick;
            //        }
            //    }
            //}

            ContextMenu menu = new ContextMenu();
            menu.MenuItems.Add(new MenuItem("Edit Language"));
            //dgvQuery.MenuClick += dgvList_MenuClick;
            //dgvQuery.ContextMenu = menu;
            dgvFilter.MenuClick += dgvList_MenuClick;
            dgvFilter.ContextMenu = menu;
        }

        protected override void LoadLanguage(string language)
        {
            foreach (Control x in this.Controls)
            {
                if (x is Label)
                {
                    clsConfigurarion.GetLabel(this.ToString(), x, language);
                }
                if (x is GroupBox || x is ExpandableGroupBox || x is Panel)
                {
                    clsConfigurarion.GetLabel(this.ToString(), x, language);
                    foreach (Control y in x.Controls)
                    {
                        if (y is Label) clsConfigurarion.GetLabel(this.ToString(), y, language);
                    }
                }
            }

            if (this.Parent is HeaderedPanel)
            {
                HeaderedPanel pln = this.Parent as HeaderedPanel;
                _title = clsConfigurarion.GetLabel(this.ToString(), "", null, language);
            }
        }

        #region IHostedApplication Members

        public void InitializeApplication()
        {
        }


        public void SetObject(object obj)
        {
            if (obj is string)
            {
                System.Collections.Specialized.NameValueCollection qscoll = System.Web.HttpUtility.ParseQueryString(obj.ToString());

                if (qscoll["id"] != null)
                {
                    string qdid = qscoll["id"];
                    qscoll.Remove("id");
                    if (qscoll.Count > 0) ReloadReport(qdid, qscoll);
                    else ReloadReport(qdid);
                }

            }
        }
        public HostedToolBarElement[] GetToolBarElements()
        {
            ArrayList objElements = new ArrayList();
            //if (IsPermis(idFilter))
            //objElements.Add(new HostedToolBarButton("Add Filter", new IconResourceHandle("add_filter.ico"), "Filter"));
            objElements.Add(new HostedToolBarSeperator());
            //if (IsPermis(idPreview))
            objElements.Add(new HostedToolBarButton("Preview", new IconResourceHandle("Preview.png"), "Preview"));
            //if (IsPermis(idExcel))
            objElements.Add(new HostedToolBarButton("Excel", new IconResourceHandle("excel.ico"), "Excel"));
            objElements.Add(new HostedToolBarButton("PDF", new IconResourceHandle("favicon.ico"), "PDF"));
            //if (IsPermis(idPrint))
            //objElements.Add(new HostedToolBarButton("Print", new IconResourceHandle("Print.png"), "P"));
            //    objElements.Add(new HostedToolBarButton("Refresh", new IconResourceHandle("Refresh.png"), "R"));
            objElements.Add(new HostedToolBarSeperator());
            //if (IsPermis(idclsTransferIn))
            //    objElements.Add(new HostedToolBarButton("clsTransfer In", new IconResourceHandle("Down.png"), "TI"));
            //if (IsPermis(idclsTransferOut))
            //    objElements.Add(new HostedToolBarButton("clsTransfer Out", new IconResourceHandle("Up.png"), "TO"));
            return (HostedToolBarElement[])objElements.ToArray(typeof(HostedToolBarElement));
        }

        public void OnToolBarButtonClick(HostedToolBarButton objButton, EventArgs objEvent)
        {
            try
            {
                sErr = "";
                string strAction = (string)objButton.Tag;

                switch (strAction)
                {
                    case "Preview":
                        Preview();
                        break;
                    case "Filter":

                        break;
                    case "Excel":
                        Excel();
                        break;
                    case "PDF":
                        Pdf();
                        break;
                    case "P":
                        break;
                    case "R":
                        RefreshList();
                        break;
                    case "TI":
                        break;
                    case "TO":

                        break;

                }
                _processStatus = strAction;
                if (sErr == "")
                    ThrowMsg("Command: " + _processStatus);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void Pdf()
        {
            SQLBuilder sql = (SQLBuilder)bsSql.DataSource;
            if (sql == null) { MessageBox.Show("Report is blank! please check", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning, false); return; }
            ReportGenerator _report = new ReportGenerator(sql, _currentQD, "", MainForm.AppConnectString, MainForm.ServerPath + "ReportTemplate\\", MainForm.ServerPath + "Report\\", "");
            _report.UserID = GetMainForm().PODInfo.USER_ID;
            _report.ValueList.Add("BUID", GetMainForm().PODInfo.Business_ID);
            //_report.Name = ((DataRowView)dgvQuery.CurrentRow.DataBoundItem)["reportcode"].ToString();
            _report.Name = _currentQD;
            ExcelFile exfile = null;
            try { exfile = _report.CreateReport(); }
            catch (Exception ex)
            {
                MessageBox.Show("There are something wrong in your input filter!");
                ThrowMsg(ex.Message);
                return;
            }

            MemoryStream ms = new MemoryStream();
            try
            {
                if (exfile != null)
                {
                    FlexCel.Render.FlexCelPdfExport pdf = new FlexCel.Render.FlexCelPdfExport(exfile);
                    pdf.Export(ms);
                }
            }
            catch { }


            DownloadGateway myDownload = new DownloadGateway(ms, _report.Name + ".pdf");

            myDownload.ContentType = "application/x-pdf";
            myDownload.StartDownload(this);
        }

        private void RefreshList()
        {
            //dgvQuery.DataSource = GetMainForm().GetTable(_strType);
        }

        private void Preview()
        {
            SQLBuilder sql = (SQLBuilder)bsSql.DataSource;
            if (sql == null) { MessageBox.Show("Report is blank! please check", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning, false); return; }
            ReportGenerator _report = new ReportGenerator(sql, _currentQD, "", MainForm.AppConnectString, MainForm.ServerPath + "ReportTemplate\\", MainForm.ServerPath + "Report\\", "");
            _report.UserID = GetMainForm().PODInfo.EMP_ID;
            _report.ValueList.Add("BUID", GetMainForm().PODInfo.Business_ID);
            ExcelFile exfile = null;
            try { exfile = _report.CreateReport(); }
            catch (Exception ex)
            {
                MessageBox.Show("There are something wrong in your input filter!");
                MainForm.AddLog("reporterror", ex.Message);
                return;
            }
            frmViewReport frmVi = new frmViewReport(_report.QdCode, GetMainForm());
            frmVi.filename = _report.QdCode;
            frmVi.Xls = exfile;
            frmVi.BringToFront();
            frmVi.Show();
        }

        private void Excel()
        {
            SQLBuilder sql = (SQLBuilder)bsSql.DataSource;
            if (sql == null) { MessageBox.Show("Report is blank! please check", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning, false); return; }
            ReportGenerator _report = new ReportGenerator(sql, _currentQD, "", MainForm.AppConnectString, MainForm.ServerPath + "ReportTemplate\\", MainForm.ServerPath + "Report\\", "");
            _report.UserID = GetMainForm().PODInfo.USER_ID;
            _report.ValueList.Add("BUID", GetMainForm().PODInfo.Business_ID);
            //_report.Name = ((DataRowView)dgvQuery.CurrentRow.DataBoundItem)["reportcode"].ToString();
            _report.Name = _currentQD;
            ExcelFile exfile = null;
            MemoryStream ms = new MemoryStream();
            try { exfile = _report.CreateReport(); }
            catch (Exception ex)
            {
                MessageBox.Show("There are something wrong in your input filter!");
                ThrowMsg(ex.Message);
                return;
            }
            exfile.Save(ms);
            DownloadGateway myDownload = new DownloadGateway(ms, _report.Name + ".xls");

            myDownload.ContentType = "application/vnd.ms-excel";
            myDownload.StartDownload(this);
        }





        #endregion

        private void QRS_Load(object sender, EventArgs e)
        {
            dgvFilter.AutoGenerateColumns = false;
            if (idAllowEditLanguage >= GetMainForm().Permission.Length || GetMainForm().Permission[idAllowEditLanguage] == 'Y')
                AllowEditLanguage();

            if (!GetMainForm().IsContainsTables(_strType)) GetMainForm().LoadDataTable(_strType);

            colIsNot.DataSource = QueryBuilder.Parsing.GetListIsNot();
            colIsNot.ValueMember = "Code";
            colIsNot.DisplayMember = "Description";

            colMode.DataSource = QueryBuilder.Parsing.GetListOperator("");
            colMode.ValueMember = "Code";
            colMode.DisplayMember = "Description";


        }

        private void ReloadReport(string qdid, System.Collections.Specialized.NameValueCollection args = null)
        {
            BUS.LIST_QDControl listqd = new BUS.LIST_QDControl();
            //_QDID = listqd.GetbyDes("HLV",_QDDESCRIPTN, ref sErr);
            _currentQD = qdid;
            SQLBuilder sql = SQLBuilder.LoadSQLBuilderFromDataBase(qdid, GetMainForm().DB, "");
            if (args != null)
            {
                foreach (Filter f in sql.Filters)
                {
                    if (args[f.Description] != null) { f.ValueFrom = f.FilterFrom = args[f.Description]; }
                    f.ValueFrom = f.FilterFrom = setDefault(f.FilterFrom);
                    f.ValueTo = f.FilterTo = setDefault(f.FilterTo);
                }
            }
            else
            {
                foreach (Filter f in sql.Filters)
                {
                    f.ValueFrom = f.FilterFrom = setDefault(f.FilterFrom);
                    f.ValueTo = f.FilterTo = setDefault(f.FilterTo);
                }
            }

            bsSql.DataSource = sql;

            dgvFilter.Text = String.Format("{0} - Filters", _currentQD);

            if (args != null) Preview();

            if (sErr != "") ThrowMsg(sErr);
        }

        private string setDefault(string p)
        {
            if (string.IsNullOrEmpty(p)) return "";
            if (p == "{T}") return DateTime.Today.ToString("yyyy-MM-dd");
            if (p == "{C}") return DateTime.Today.ToString("yyyy0MM");
            if (p == "{FP}") return DateTime.Today.ToString("yyyy001");
            if (p == "{EP}") return DateTime.Today.ToString("yyyy012");
            if (p == "{FM}") return new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1).ToString("yyyy-MM-dd");
            if (p == "{EM}") return new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.DaysInMonth(DateTime.Today.Year, DateTime.Today.Month)).ToString("yyyy-MM-dd");
            if (p == "{FY}") return new DateTime(DateTime.Today.Year, 1, 1).ToString("yyyy-MM-dd");
            if (p == "{EY}") new DateTime(DateTime.Today.Year, 12, 31).ToString("yyyy-MM-dd");
            return p;
        }
        private void LoadGroupReport()
        {
            //BUS.csreportgroupsControl ctr = new BUS.csreportgroupsControl();
            //DataTable dt =  ctr.GetAll(ref sErr);
            //DataRow dr = dt.NewRow();
            //dt.Rows.Add(dr);
            //cboGroupReport.DataSource = dt;
            //cboGroupReport.DisplayMember = "Name";
            //cboGroupReport.ValueMember = "ReportGroup";
        }

        private void cboGroupReport_SelectedValueChanged(object sender, EventArgs e)
        {
            //if (cboGroupReport.Text != "" && cboGroupReport.Text != "System.Data.DataRowView")
            //{
            //    BUS.csreportgroupdetailControl ctrdel = new BUS.csreportgroupdetailControl();
            //    DataTable dt = ctrdel.GetbyGroup(_DB, cboGroupReport.SelectedValue.ToString(), ref sErr);
            //    dgvQuery.DataSource = dt;
            //}
            //else
            //{
            //    if (!GetMainForm().IsContainsTables(_strType))
            //        GetMainForm().LoadDataTable(_strType);
            //    dgvQuery.DataSource = GetMainForm().GetTable(_strType);
            //}
        }



        private void dgvFilter_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex == -1)
                return;
            try
            {
                SQLBuilder sql = (SQLBuilder)bsSql.DataSource;
                if (sql == null) { MessageBox.Show("Report is blank! please check", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning, false); return; }

                QueryBuilder.Filter f = sql.Filters[e.RowIndex];

                if (f.Node.MyCode.Length > 2 && f.Node.MyCode.Substring(0, 2) != "__")
                {
                    if (f.Node.FType == "SDN" || f.Node.FType == "D")
                    {
                        frmDateFilterSelect frm = new frmDateFilterSelect(f.Node.FType);
                        frm.FilterFrom = f.FilterFrom;
                        frm.FilterTo = f.FilterTo;
                        frm.FormClosed += (form, args) =>
                        {
                            if (((Form)form).DialogResult == DialogResult.OK)
                            {
                                f.FilterFrom = f.ValueFrom = frm.FilterFrom;
                                f.FilterTo = f.ValueTo = frm.FilterTo;
                                dgvFilter.Update();
                                //  bsSql.DataSource = sql;
                            }
                        };
                        frm.ShowDialog();
                    }
                    else
                    {
                        frmFilterSelect frm = new frmFilterSelect(MainForm.AppConnectString, sql, e.RowIndex);
                        frm.FilterFrom = dgvFilter.Rows[e.RowIndex].Cells["FilterFrom"].Value.ToString();
                        frm.FilterTo = dgvFilter.Rows[e.RowIndex].Cells["FilterTo"].Value.ToString();
                        frm.FormClosed += (form, args) =>
                        {
                            if (((Form)form).DialogResult == DialogResult.OK)
                            {
                                f.FilterFrom = f.ValueFrom = frm.FilterFrom;
                                f.FilterTo = f.ValueTo = frm.FilterTo;
                                dgvFilter.Update();// bsSql.DataSource = sql;
                            }
                        };
                        frm.ShowDialog();
                    }
                }
                else if (f.Node.MyCode.Substring(0, 2) == "__")
                {
                    if (f.Node.FType == "SDN" || f.Node.FType == "D")
                    {
                        frmDateFilterSelect frm = new frmDateFilterSelect(f.Node.FType);
                        frm.FilterFrom = dgvFilter.Rows[e.RowIndex].Cells["FilterFrom"].Value.ToString();
                        frm.FilterTo = dgvFilter.Rows[e.RowIndex].Cells["FilterTo"].Value.ToString();
                        frm.FormClosed += (form, args) =>
                        {
                            if (((Form)form).DialogResult == DialogResult.OK)
                            {
                                f.FilterFrom = f.ValueFrom = frm.FilterFrom;
                                f.FilterTo = f.ValueTo = frm.FilterTo;
                                dgvFilter.Update(); //bsSql.DataSource = sql;
                            }
                        };
                        frm.ShowDialog();
                    }
                }
            }
            catch (Exception ex)
            {
                ThrowMsg(ex.Message);
            }
        }


        private void dgvFilter_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                try
                {
                    if (dgvFilter.Columns[e.ColumnIndex].DataPropertyName == "FilterFrom" || dgvFilter.Columns[e.ColumnIndex].DataPropertyName == "FilterTo")
                    {
                        SQLBuilder sql = (SQLBuilder)bsSql.DataSource;
                        if (sql == null) { MessageBox.Show("Report is blank! please check", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Warning, false); return; }
                        //SqlBuilder_Change();
                        QueryBuilder.Filter x = sql.Filters[e.RowIndex];
                        string value = x.FilterFrom;
                        string ToValue = x.FilterTo;
                        if (x != null)
                        {
                            if ((x.Node.FType == "D" || x.Node.FType == "SDN") && Regex.IsMatch(value, _datePaterm))
                            {
                                string yearnow = DateTime.Now.Year.ToString("0000");
                                string[] arr = value.Split('.');

                                if (arr.Length == 3)
                                {
                                    if (arr[2].Length < 4)
                                        arr[2] = yearnow.Substring(0, 4 - arr[2].Length) + arr[2];
                                    if (x.Node.FType == "D")
                                    {
                                        value = String.Format("{0}-{1}-{2}", arr[2], arr[1], arr[0]);
                                    }
                                    else
                                        value = arr[2] + arr[1] + arr[0];
                                }
                                else
                                {
                                    arr = value.Split('-');

                                    if (arr.Length == 3)
                                    {
                                        if (arr[2].Length < 4)
                                            arr[2] = yearnow.Substring(0, 4 - arr[2].Length) + arr[2];
                                        if (x.Node.FType == "D")
                                        {
                                            value = String.Format("{0}-{1}-{2}", arr[2], arr[1], arr[0]);
                                        }
                                        else
                                            value = arr[2] + arr[1] + arr[0];
                                    }
                                    else
                                    {
                                        arr = value.Split('/');

                                        if (arr.Length == 3)
                                        {
                                            if (arr[2].Length < 4)
                                                arr[2] = yearnow.Substring(0, 4 - arr[2].Length) + arr[2];
                                            if (x.Node.FType == "D")
                                            {
                                                value = String.Format("{0}-{1}-{2}", arr[2], arr[1], arr[0]);
                                            }
                                            else
                                                value = arr[2] + arr[1] + arr[0];
                                        }
                                    }
                                    x.FilterFrom = x.ValueFrom = value;
                                    // bsSql.DataSource = sql;
                                }
                            }
                            else
                            {
                                if (dgvFilter.Columns[e.ColumnIndex].DataPropertyName == "FilterFrom")
                                    x.FilterFrom = x.ValueFrom = value;
                                else if (dgvFilter.Columns[e.ColumnIndex].DataPropertyName == "FilterTo")
                                    x.FilterTo = x.ValueTo = dgvFilter.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                                // bsSql.DataSource = sql;
                            }
                        }
                    }
                }
                catch { }
            }
        }


    }
}